package shark.scheduler.model;

import org.springframework.beans.factory.annotation.Autowired;
import shark.common.utils.SpringContextUtils;
import shark.scheduler.enums.TaskStatus;
import shark.scheduler.handler.DistributedLockHandler;
import shark.scheduler.spi.entity.ScheduledCron;
import shark.scheduler.spi.mapper.ScheduledCronMapper;

public interface SharkScheduler extends Runnable{

    /**
     * 实现控制定时任务启用或禁用的功能
     */
    @Override
    default void run() {
        DistributedLockHandler distributedLockHandler = SpringContextUtils.getBean(DistributedLockHandler.class);
        ScheduledCronMapper scheduledCronMapper = SpringContextUtils.getBean(ScheduledCronMapper.class);
        ScheduledCron scheduledCron = scheduledCronMapper.findByKey(this.getClass().getName());
        if (TaskStatus.DISABLED.getCode().equals(scheduledCron.getStatus())) {
            // 任务是禁用状态,且获取锁失败
            return;
        }

        Lock lock = new Lock(this.getClass().getName(), "lock");
        if (!distributedLockHandler.tryLock(lock)) {
            return;
        }
        execute();
        distributedLockHandler.releaseLock(lock);
    }

    /**
     * 定时任务方法
     */
    void execute();
}
